<template>
  <view class="order-list-page">
    <!-- 顶部导航栏 -->
    <view class="nav-tabs">
      <view 
        class="nav-tab" 
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        全部
      </view>
      <view 
        class="nav-tab" 
        :class="{ active: activeTab === 'inProgress' }"
        @click="switchTab('inProgress')"
      >
        进行中
      </view>
      <!--
      <view 
        class="nav-tab" 
        :class="{ active: activeTab === 'pending' }"
        @click="switchTab('pending')"
      >
        待付款
      </view>
      -->
      <view 
        class="nav-tab" 
        :class="{ active: activeTab === 'completed' }"
        @click="switchTab('completed')"
      >
        已完成
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <!-- 加载状态 -->
      <view class="loading-container" v-if="isLoading">
        <text class="loading-text">正在加载订单列表...</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-container" v-else-if="filteredOrders.length === 0">
        <text class="empty-text">暂无订单数据</text>
      </view>
      
      <!-- 订单列表 -->
      <view 
        class="order-card" 
        v-else
        v-for="(order, index) in filteredOrders" 
        :key="index"
        @click="goToOrderDetail(order)"
      >
        <!-- 订单头部信息 -->
        <view class="order-header">
          <view class="order-left">
            <view class="station-info">
              <text class="station-name">{{ order.stationName }}</text>
            </view>
            <text class="order-time">{{ order.time }}</text>
          </view>
          <view class="order-status" :class="order.status">
            {{ getStatusText(order.status) }}
          </view>
        </view>

        <!-- 订单金额信息 -->
        <view class="order-amount">
          <text v-if="order.status === 'inProgress' || order.status === 'starting' || order.status === 'stopping'" class="amount-value">--</text>
          <text v-else class="amount-value">¥{{ order.amount }}</text>
        </view>

        <!-- 订单详情信息 -->
        <view class="order-details">
          <text v-if="order.status === 'inProgress' || order.status === 'starting' || order.status === 'stopping'" class="duration">
            用时 {{ order.duration }}
          </text>
          <text v-else class="charge-info">
            充电 {{ order.kwh ? order.kwh + ' 度' : '度数暂无' }} · 用时 {{ order.duration }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getMyChargeOrderList } from '@/api/charging/index.js'

export default {
  data() {
    return {
      activeTab: 'all',
      orders: [], // 原始订单数据
      isLoading: false, // 加载状态
      orderList: [] // 处理后的订单列表
    }
  },
  
  computed: {
    filteredOrders() {
      if (this.activeTab === 'all') {
        // 全部选项卡显示所有状态的订单
        return this.orderList;
      } else if (this.activeTab === 'inProgress') {
        // 进行中选项卡只显示状态为2的订单
        return this.orderList.filter(order => order.rawData.payState === 2);
      } else if (this.activeTab === 'completed') {
        // 已完成选项卡显示状态为4和5的订单
        return this.orderList.filter(order => order.rawData.payState === 4 || order.rawData.payState === 5);
      }
      return this.orderList;
    }
  },
  
  onShow() {
    // 页面显示时获取订单列表
    this.getOrderList();
  },
  
  methods: {
    // 获取订单列表
    getOrderList() {
      this.isLoading = true;
      
      const params = {
        page: 1,
        rows: 10000
        // chargeState 不传，获取所有状态的订单
      };
      
      console.log('获取订单列表，参数:', params);
      
      getMyChargeOrderList(params).then(res => {
        console.log('订单列表响应:', res);
        this.isLoading = false;
        
        if (res && res.code === 0 && res.success && res.data && res.data.records) {
          this.orders = res.data.records;
          this.processOrderData();
        } else {
          console.error('获取订单列表失败:', res.msg);
          uni.showToast({
            title: res.msg || '获取订单列表失败',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('订单列表接口调用失败:', error);
        this.isLoading = false;
        uni.showToast({
          title: error.msg || '网络请求失败',
          icon: 'none'
        });
      });
    },
    
    // 处理订单数据，分类为进行中和已完成
    processOrderData() {
      this.orderList = this.orders.map(order => {
        // 根据payState字段判断订单状态
        let status = 'unknown'; // 默认未知
        
        switch (order.payState) {
          case 1:
            status = 'starting'; // 启动中
            break;
          case 2:
            status = 'inProgress'; // 进行中
            break;
          case 3:
            status = 'stopping'; // 停止中
            break;
          case 4:
            status = 'completed'; // 已完成
            break;
          case 5:
            status = 'completed'; // 已完成
            break;
          default:
            status = 'unknown';
        }
        
        // 计算充电时长
        let duration = '暂无';
        if (order.startTime && order.endTime) {
          const startTime = new Date(order.startTime);
          const endTime = new Date(order.endTime);
          const diffMs = endTime - startTime;
          const diffMins = Math.floor(diffMs / (1000 * 60));
          const diffSecs = Math.floor((diffMs % (1000 * 60)) / 1000);
          duration = `${diffMins} 分 ${diffSecs} 秒`;
        }
        
        // 格式化时间
        let time = '未知';
        if (order.createTime) {
          const date = new Date(order.createTime);
          time = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        }
        
        // 获取场站名称，如果没有则从deviceCode解析
        let stationName = order.stationName;
        if (!stationName && order.deviceCode) {
          // 从deviceCode中提取场站信息
          const parts = order.deviceCode.split('.');
          if (parts.length > 0) {
            stationName = `场站${parts[0].split('/').pop()}`;
          }
        }
        
        return {
          id: order.id,
          orderNumber: order.orderNumber,
          chargeOrderId: order.chargeOrderId,
          stationName: stationName || '未知场站',
          time: time,
          status: status,
          amount: order.orderRealPrice ? order.orderRealPrice.toFixed(2) : '0.00',
          duration: duration,
          kwh: order.totalPower,
          // 原始数据，用于详情页跳转
          rawData: order
        };
      });
      
      console.log('处理后的订单列表:', this.orderList);
    },
    
    switchTab(tab) {
      this.activeTab = tab;
    },
    
    getStatusText(status) {
      const statusMap = {
        'starting': '启动中',
        'inProgress': '进行中',
        'stopping': '停止中',
        'completed': '已完成',
        'unknown': '未知'
      };
      return statusMap[status] || '';
    },
    
    goToOrderDetail(order) {
      console.log('跳转订单，参数:', order);
      
      // 根据订单状态决定跳转目标
      if (order.status === 'inProgress') {
        // 进行中的订单跳转到充电页面
        console.log('进行中订单，跳转到充电页面');
        uni.navigateTo({
          url: `/pages/charging/index?orderNum=${order.orderNumber}`
        });
      } else {
        // 其他状态的订单跳转到订单详情页面
        console.log('其他状态订单，跳转到订单详情页');
        uni.navigateTo({
          url: `/pages/orderDetail/orderDetail?orderNum=${order.orderNumber}`
        });
      }
    }
  }
}
</script>

<style scoped>
.order-list-page {
  background: #fbfbfb;
  min-height: 100vh;
  padding: 0;
}

/* 顶部导航栏 */
.nav-tabs {
  display: flex;
  background: #fff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-tab {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
}

.nav-tab.active {
  color: #333;
  font-weight: bold;
}

.nav-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #ff6b35;
  border-radius: 2rpx;
}

/* 订单列表 */
.order-list {
  padding: 20rpx 30rpx;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 空状态 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.order-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.order-left {
  flex: 1;
}

.station-info {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.station-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

.order-status {
  font-size: 28rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-weight: bold;
}

.order-status.inProgress {
  color: #ff6b35;
}

.order-status.starting {
  color: #4CAF50;
}

.order-status.stopping {
  color: #FF9800;
}

.order-status.completed {
  color: #666;
}

.order-status.unknown {
  color: #999;
}

/* 订单金额 */
.order-amount {
  margin-bottom: 15rpx;
}

.amount-dash {
  font-size: 32rpx;
  color: #ccc;
  font-weight: bold;
}

.amount-value {
  font-size: 36rpx;
  color: #ff6700;
  font-weight: bold;
}

/* 订单详情 */
.order-details {
  font-size: 24rpx;
  font-weight: bold;
  color: #999;
}

.duration {
  color: #999;
}

.charge-info {
  color: #999;
}
</style> 